import React from "react";
import { RouteComponentProps } from 'react-router';
import { getNewsList } from '../../apiList/api'
import { parseTime } from '../../utils/jcore/time'
import { session } from '../../utils/jcore/storage'
import { getQueryString } from '../../utils/jcore/page'
import NewsDetailCom, { IFNewsItem } from './NewsDetailCom'
import BackPageTop from '../../components/BackPageTop'
import css from './NewsGroup.less'

type P = {} & RouteComponentProps

type S = {
    page: number;
    currentId: string;
    loadEnd: boolean;
    noRepeat: boolean;
    showInfo: boolean;
    newsList: IFNewsItem[];
}

let scrollTop = 0

export default class NewsGroup extends React.Component<P, S> {
    static defaultProps = {
        message: 'NewsGroup'
    }
    constructor(props: P) {
        super(props)
        this.state = {
            page: 1,
            currentId: '',
            loadEnd: false,
            noRepeat: false,
            showInfo: false,
            newsList: []
        }
    }
    componentDidMount() {
        this.getList()
        window.addEventListener('scroll', this.onScroll, false)
    }
    componentWillUnmount() {
        window.removeEventListener('scroll', this.onScroll)
    }
    // 获取数据列表
    async getList() {
        const { page, noRepeat } = this.state
        if (noRepeat) {
            console.log(noRepeat, '重复请求')
            return
        }
        this.setState({ noRepeat: true })
        let res = await getNewsList({ page })
        let list = this.state.newsList
        this.setState({ newsList: list.concat(res) })
        if (!res || res.length < 10) {
            this.setState({ loadEnd: true })
            console.log('没有了')
        }
        this.setState({ noRepeat: false, page: page + 1 })
    }
    // 展示新闻详情
    openNewsInfo(item: IFNewsItem) {
        session.set('scrollTopVal', scrollTop)
        this.setState({ currentId: item.id, showInfo: true })
    }
    // 跳转到新闻详情
    linkNewsInfo(e: React.FormEvent<HTMLButtonElement>, item: IFNewsItem) {
        e.stopPropagation()
        this.props.history.push({
            pathname: '/news/detail/page',
            search: getQueryString({ id: item.id })
        })
    }
    // 滚动事件
    onScroll = () => {
        let dom = document.querySelector('#slide_load_more')
        if (!dom) {
            console.log('未获取到Dom,请设置容器id `slide_load_more` ')
            return
        }
        let innerHeight = dom.clientHeight
        let outerHeight = document.documentElement.clientHeight
        scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        if (scrollTop > innerHeight - outerHeight - 100) {
            if (this.state.loadEnd) {
                console.log('加载完毕')
            } else {
                this.getList()
            }
        }
    }
    closeNewsInfo = () => {
        this.setState({ showInfo: false, currentId: '' }, () => {
            // 同步滚动条位置
            let scrollTopVal = session.get('scrollTopVal') || 0
            document.documentElement.scrollTop = scrollTopVal
        })
    }
    createNewsInfo(currentId: string): React.ReactElement {
        return (
            <div>
                <div style={{ cursor: "pointer", color: "#551a8b" }} onClick={this.closeNewsInfo}>返回列表</div>
                <NewsDetailCom closeNewsInfo={this.closeNewsInfo} id={currentId} />
            </div>
        )
    }
    render() {
        const { newsList, currentId, showInfo, loadEnd } = this.state
        return (
            <div>
                <div style={showInfo ? { display: "none" } : {}} className={css.news_max} id="slide_load_more" >
                    {
                        newsList.map(item => {
                            return (
                                <div key={item.id} className={css.news_item_box} onClick={() => this.openNewsInfo(item)}>
                                    <div className={css.img_box}>
                                        <img className={css.news_cover} src={item.cover} alt="err" />
                                    </div>
                                    <div className={css.content_box}>
                                        <div className={css.title}>{item.title}</div>
                                        <p>时间: {parseTime(item.createTime)}</p>
                                        <button onClick={(e) => this.linkNewsInfo(e, item)} >跳转详情页</button>
                                    </div>
                                </div>
                            )
                        })
                    }
                    <BackPageTop />
                    {loadEnd && <div style={{ textAlign: "center" }} >没有更多了</div>}
                </div>
                {showInfo && this.createNewsInfo(currentId)}
            </div>
        )
    }
}